from django.shortcuts import render, HttpResponse, redirect
from app01.utils.pagination import Pagination
from app01 import models
"""部门列表"""


def depart_list(request):
    queryset = models.Department.objects.all()
    page_object = Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, 'depart_list.html', context)


"""添加部门"""


def depart_add(request):
    if request.method == "GET":
        return render(request, "depart_add.html")
    data = request.POST.get("title")
    models.Department.objects.create(title=data)
    return redirect("/depart/list/")


"""删除部门"""


def depart_delete(request):
    nid = request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")


"""修改部门"""


def depart_edit(request, nid):
    if request.method == "GET":
        # 根据nid获取他的数据
        row_data = models.Department.objects.filter(id=nid).first()
        return render(request, "depart_edit.html", {"row_data": row_data})
    data = request.POST.get("title")
    models.Department.objects.filter(id=nid).update(title=data)
    return redirect("/depart/list/")

def depart_multi(request):
    """批量上传Excel文件"""
    from openpyxl import load_workbook
    # 1.获取用户上传的文件对象
    file_object = request.FILES.get("exc")
    print(type(file_object))
    print(file_object)
    # 2.对象传递给openpyxl，用openpyxl读取文件的内容
    # 直接打开Excel并读取内容
    # wb = load_workbook("文件路径/文件对象")
    wb = load_workbook(file_object)
    # 读取文件中第一张表
    sheet = wb.worksheets[0]
    # 读取表的第一行第一列
    # cell = sheet.cell(1,1)
    # print(cell.value)
    # 3.循环获取每一行的数据
    # sheet.rows从第一行开始取
    # sheet.iter_rows(min_row=2)  从第二行开始读取
    for row in sheet.iter_rows(min_row=2):
        # print(row[0].value)
        text = row[0].value
        exists = models.Department.objects.filter(title=text).exists()
        if not exists:
            models.Department.objects.create(title=text)
    f = open(file_object.name,mode="wb")
    for chunk in file_object.chunks():
        f.write(chunk)
    f.close()
    return redirect("/depart/list/")